const path = require('path');
const fs = require('fs');
const axios = require('axios');
const config = require('../config');

// 设置axios超时
axios.defaults.timeout = 5000;

// 模拟K线数据文件
const KLINE_DATA_FILE = path.join(__dirname, '../data/kline_data.json');
const SYMBOLS_FILE = path.join(__dirname, '../data/symbols.json');

// 确保数据目录存在
const ensureDataDirExists = () => {
  const dataDir = path.join(__dirname, '../data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
  }
};

// 初始化交易对数据
const initSymbols = () => {
  ensureDataDirExists();
  if (!fs.existsSync(SYMBOLS_FILE)) {
    // 模拟交易对数据
    const symbols = [
      { symbol: 'BTCUSDT', name: 'Bitcoin/USDT' },
      { symbol: 'ETHUSDT', name: 'Ethereum/USDT' },
      { symbol: 'BNBUSDT', name: 'Binance Coin/USDT' },
      { symbol: 'SOLUSDT', name: 'Solana/USDT' },
      { symbol: 'ADAUSDT', name: 'Cardano/USDT' },
      { symbol: 'DOTUSDT', name: 'Polkadot/USDT' },
      { symbol: 'DOGEUSDT', name: 'Dogecoin/USDT' },
      { symbol: 'AVAXUSDT', name: 'Avalanche/USDT' },
      { symbol: 'LINKUSDT', name: 'Chainlink/USDT' },
      { symbol: 'LTCUSDT', name: 'Litecoin/USDT' }
    ];
    fs.writeFileSync(SYMBOLS_FILE, JSON.stringify(symbols, null, 2));
  }
};

// 初始化K线数据
const initKlineData = () => {
  ensureDataDirExists();
  if (!fs.existsSync(KLINE_DATA_FILE)) {
    fs.writeFileSync(KLINE_DATA_FILE, JSON.stringify({}));
  }
};

// 获取交易对列表
exports.getSymbols = () => {
  initSymbols();
  return JSON.parse(fs.readFileSync(SYMBOLS_FILE, 'utf8'));
};

// 生成模拟K线数据
const generateMockKlineData = (symbol, interval, startTime, endTime) => {
  // 解析时间参数
  const start = startTime ? new Date(startTime) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  const end = endTime ? new Date(endTime) : new Date();

  // 计算时间间隔对应的毫秒数
  let intervalMs = 60 * 1000; // 默认1分钟
  switch (interval) {
    case '15m': intervalMs = 15 * 60 * 1000; break;
    case '30m': intervalMs = 30 * 60 * 1000; break;
    case '1h': intervalMs = 60 * 60 * 1000; break;
    case '4h': intervalMs = 4 * 60 * 60 * 1000; break;
    case '1d': intervalMs = 24 * 60 * 60 * 1000; break;
  }

  // 生成K线数据
  const klineData = [];
  let currentTime = start;
  let openPrice = Math.random() * 10000 + 40000; // 随机初始价格

  while (currentTime <= end) {
    // 随机生成价格波动
    const change = (Math.random() - 0.5) * 200;
    const highPrice = openPrice + Math.random() * 100;
    const lowPrice = openPrice - Math.random() * 100;
    const closePrice = openPrice + change;
    const volume = Math.random() * 100 + 10;

    klineData.push({
      open: openPrice.toFixed(2),
      high: highPrice.toFixed(2),
      low: lowPrice.toFixed(2),
      close: closePrice.toFixed(2),
      volume: volume.toFixed(2),
      timestamp: currentTime.toISOString()
    });

    // 更新下一根K线的开盘价
    openPrice = closePrice;
    // 移动到下一个时间间隔
    currentTime = new Date(currentTime.getTime() + intervalMs);
  }

  return klineData;
};

// 获取K线数据
exports.getKlineData = async (symbol, interval = '1h', startTime, endTime) => {
  initKlineData();

  try {
    // 尝试从Binance API获取真实数据
    const response = await axios.get(
      `${config.binance.baseUrl}/api/v3/klines`,
      {
        params: {
          symbol: symbol,
          interval: interval,
          startTime: startTime ? new Date(startTime).getTime() : undefined,
          endTime: endTime ? new Date(endTime).getTime() : undefined,
          limit: 1000
        },
        headers: {
          'X-MBX-APIKEY': config.binance.apiKey
        }
      }
    );

    // 格式化API返回的数据
    const formattedData = response.data.map(item => ({
      open: item[1],
      high: item[2],
      low: item[3],
      close: item[4],
      volume: item[5],
      timestamp: new Date(item[0]).toISOString()
    }));

    return formattedData;
  } catch (error) {
    console.error('获取K线数据失败，使用模拟数据:', error.message);
    console.error('完整错误信息:', error);
    console.error('请求参数:', { symbol, interval, startTime, endTime });
    // 如果API请求失败，使用模拟数据
    return generateMockKlineData(symbol, interval, startTime, endTime);
  }
};

// 获取最新K线数据
exports.getLatestKline = async (symbol, interval = '1h') => {
  try {
    // 尝试从Binance API获取最新数据
    const response = await axios.get(
      `${config.binance.baseUrl}/api/v3/klines`,
      {
        params: {
          symbol: symbol,
          interval: interval,
          limit: 1
        },
        headers: {
          'X-MBX-APIKEY': config.binance.apiKey
        }
      }
    );

    if (response.data.length === 0) {
      throw new Error('未获取到K线数据');
    }

    const item = response.data[0];
    return {
      symbol: symbol,
      open: item[1],
      high: item[2],
      low: item[3],
      close: item[4],
      volume: item[5],
      timestamp: new Date(item[0]).toISOString()
    };
  } catch (error) {
    console.error('获取最新K线数据失败，使用模拟数据:', error.message);
    console.error('完整错误信息:', error);
    console.error('请求参数:', { symbol, interval });
    // 生成模拟数据
    const now = new Date();
    const oneIntervalAgo = new Date(now.getTime() - 60 * 60 * 1000); // 假设1小时间隔
    const mockData = generateMockKlineData(symbol, interval, oneIntervalAgo, now);
    return mockData[mockData.length - 1];
  }
};